<?php


namespace app\web\controller;


use app\api\controller\v2\Auth;
use app\common\cachemodel\MiniAppUser;
use app\common\cachemodel\ZlGoddessState;
use app\common\lib\exception\ApiException;
use app\common\lib\Jssdk;
use app\common\lib\Util;
use app\common\model\Recode as RecodeModel;
use app\common\model\User;
use think\Cache;
use think\Controller;
use think\Env;
use think\Exception;
use think\Log;

class ActiveFortuneYearNew extends Controller
{
    public const AVATAR_WIDTH = 60;//头像宽度
    public const AVATAR_HEIGHT = 60;//头像高度
    public const RANDOM_WORDS_INDEX_EXPIRED = 1296000;//关键字过期时间15天

    protected function _initialize(): void
    {
        parent::_initialize();
        $res = Util::androidVersion('2.2.0');
        $this->assign('version', $res);
    }

    protected $words = [
        '暴富', '暴瘦', '爆发', '发财', '革新',
        '安逸', '潇洒', '喜悦', '开心', '狂喜',
        '愉悦', '痛快', '得意', '欢乐', '快活',
        '欣喜', '幸福', '荣耀', '幸运', '惬意',
        '如意', '兴旺', '美满', '舒畅', '完美',
    ];

    protected $words_four = [
        '一夜暴富', '一夜成名', '健健康康', '生龙活虎', '功成名就',
        '独占鳌头', '硕果累累', '欣欣向荣', '蒸蒸日上', '展翅高飞',
        '相濡以沫', '前程似锦', '春风得意', '风生水起', '出类拔萃',
        '名列前茅', '德才兼备', '激情四射', '激情似火', '意气风发',
        '神采奕奕', '心满意足', '安居乐业', '称心如意', '桃花朵朵',
        '如愿以偿', '大展宏图', '大功告成', '丰衣足食', '和和睦睦',
        '横扫千军', '无懈可击', '日进斗金', '无忧无虑', '步步高升',
        '飞黄腾达', '平步青云', '登峰造极', '建功立业', '福星高照',
        '金榜题名', '一鸣惊人', '眉飞色舞'
    ];


    public function index()
    {
        //是否是测试环境
        $isTest = false;
        $isInApp = 0;//0：不是在app里打开；1：是在app里打开；
        $type = 0;//0：用户未登录；1：用户已登录；
        $app_type = '';
        $uid = '';
        $signPackage = [];
        $sign = -1;
        $moon = -1;
        $asc = -1;

        if (!$isTest)
        {
            $headers = $this->request->header();
        }

        $not_in_app_page = 1;//页面里显示第几页
        $not_in_app_is_login = 0;//不在App里的话，是否登录：0：没有登录；1：已登录；

        if (isset($headers['sign']))
        {//在App里请求
            $isInApp = 1;
            $app_type = $headers['app-type'];
            $type = 1;
            //校验token
            try
            {
                $auth = new Auth();
                $auth->checkRequestAuth();
                $uid = $auth->user['id'];
                $map = ['uid' => $uid, 'isself' => 1];
                $recode_info = (new RecodeModel())->getSelfRecode($map);
                if ($recode_info && isset($recode_info['sun']))
                {
                    $sign = explode('-', $recode_info['sun'])[0];
                    $moon = explode('-', $recode_info['moon'])[0];
                    $asc = explode('-', $recode_info['asc'])[0];
                }
            }
            catch (Exception $e)
            {
                Log::write('年度报告_在App里请求异常:' . $e->getMessage(), 'error', true);
            }
        } else
        {//在App外请求
            $token = session('active_fortune_year_new.token');
//            $token = $this->request->param('token');
            if ($token)
            {//开始解密，token是小程序h5生成的
                try
                {
                    // access-token AES解密
                    $accessUserToken = $this->decryptWithOpenssl($token);
                    if (empty($accessUserToken)) return false;
                    if (!preg_match('/||/', $accessUserToken)) return false;
                    [$token, $miniId] = explode('||', $accessUserToken);
                    $miniInfo = (new MiniAppUser())->getMiniAppInfo($miniId);

                    if (!$miniInfo || ($miniInfo && $miniInfo['access_token'] !== $token) || $this->request->time() > $miniInfo['expires_in'] || $miniInfo['status'] != 0)
                    {   // 判断token是否过期 并且账户状态正常
                        throw new ApiException('登录失效', 200, config('code.denied'));
                    }
                    $uid = (int)($miniInfo['uid']);
                    $map = ['uid' => $uid, 'isself' => 1];
                    $recode_info = (new RecodeModel())->getSelfRecode($map);
                    if ($recode_info && isset($recode_info['sun']))
                    {
                        $sign = explode('-', $recode_info['sun'])[0];
                        $moon = explode('-', $recode_info['moon'])[0];
                        $asc = explode('-', $recode_info['asc'])[0];
                        $not_in_app_page = 3;//设置请求第几页
                        $not_in_app_is_login = 1;//登录成功
                        $type = 1;
                    }
                }
                catch (Exception $e)
                {
                    Log::write('年度报告_在App外请求异常:' . $e->getMessage(), 'error', true);
                }
            }

            $ua = $_SERVER['HTTP_USER_AGENT'];
            if (strpos($ua, 'MicroMessenger') === false && strpos($ua, 'Windows Phone') === false)
            {
                //使用其他浏览器打开的
            } else
            {
                //微信登录
            }
        }

        $signPackage = (new Jssdk())->getSignPackage();
        $video_info = $this->getVideoWithSign($sign);

        $this->assign('data', [
            'not_in_app_login_url' => Env::get('host.wap_domain') . '/zhunle_wap_login?callback_url=' . urlencode(Env::get('host.domain') . '/web/active_fortune_year_new/callback_h5'),
            'not_in_app_is_login' => $not_in_app_is_login,
            'not_in_app_page' => $not_in_app_page,

            'video_url' => $video_info['url'],
            'video_thumb' => $video_info['thumb'],

            'host' => $this->request->domain(),
            'ossHost' => Env::get('host.photo') . 'web',
//            'ossHost' => Env::get('host.domain'),
            'title' => '准了2020年度运势盘点',
            'share_title' => '快来签收你的2020年度运势盘点～', // 分享标题
            'share_introduction' => '听说里面还藏着来年的好运和惊喜！', // 分享描述
            'signPackage' => $signPackage,
            'type' => $type,
            'uid' => $uid,
            'sign' => $sign,//只有$type=1，并且有自己档案的时候，才显示自己的默认选中星座，否则默认为-1
            'moon' => $moon,
            'asc' => $asc,
            'isInApp' => $isInApp,
            'app_type' => $app_type
        ]);

        return $this->fetch('index');
    }

    public function callback_h5()
    {
        $token = $this->request->param('token');
        session('active_fortune_year_new.token', $token);
        $this->redirect('/web/active_fortune_year_new/index');
    }

    //开始生成用户头像保存到本地
    public function createAvatar()
    {
        $uid = htmlspecialchars(trim(input('get.uid/s')));
        $type = htmlspecialchars(trim(input('get.type/d')));

        $avatar_url = '';
        if (1 === (int)$type)
        {
            try
            {
                $user = (new User())->getUserinfo(['id' => $uid]);

                if (preg_match('/^http(s?):\/\/*/', $user['avatar']))
                {
                    $avatar_url = $user['avatar'];
                } else if (!empty($user['avatar']))
                {
                    $avatar_url = Env::get('host.photo') . $user['avatar'];
                }
            }
            catch (ApiException $e)
            {
            }
        }
        if (!empty($avatar_url))
        {
            $this->circleImg($avatar_url, $uid . '.png');
        }

        return show(config('code.success'), '请求成功', []);
    }

    //获取报告index
    public function getReport()
    {
        $uid = htmlspecialchars(trim(input('get.uid/s')));
        //0：App未登录；1：App已登录；2：微信登录
        $type = htmlspecialchars(trim(input('get.type/d')));
        $name = '';
        switch ($type)
        {
            case 0:
                $name = '匿名用户';
                break;
            case 1:
                $user = (new User())->getUserinfo(['id' => $uid]);
                $name = $user['nickname'];
                break;
        }

        //获取缓存的indexs
        $cache_index = Cache::get('active_fortune_year_new.index.' . $uid);
        $cache_index_word_four_1 = Cache::get('active_fortune_year_new.index_word_four_1.' . $uid);
        $cache_index_word_four_2 = Cache::get('active_fortune_year_new.index_word_four_2.' . $uid);
        $cache_index_word_four_3 = Cache::get('active_fortune_year_new.index_word_four_3.' . $uid);

        if (!empty($cache_index) && !empty($cache_index_word_four_1) && !empty($cache_index_word_four_2) && !empty($cache_index_word_four_3))
        {//如果不为空
            $index = $cache_index;
            $index_word = $this->words[$index];
            //四个字随机
            $word_four_arr = [$cache_index_word_four_1, $cache_index_word_four_2, $cache_index_word_four_3];
        } else
        {
            //两个字随机
            $index = rand(0, count($this->words) - 1);
            $index_word = $this->words[$index];
            //四个字随机
            $word_four_arr = array_rand($this->words_four, 3);

            //存储用户的index，防止用户下次进来不一样
            Cache::set('active_fortune_year_new.index.' . $uid, $index, self::RANDOM_WORDS_INDEX_EXPIRED);
            Cache::set('active_fortune_year_new.index_word_four_1.' . $uid, $word_four_arr[0], self::RANDOM_WORDS_INDEX_EXPIRED);
            Cache::set('active_fortune_year_new.index_word_four_2.' . $uid, $word_four_arr[1], self::RANDOM_WORDS_INDEX_EXPIRED);
            Cache::set('active_fortune_year_new.index_word_four_3.' . $uid, $word_four_arr[2], self::RANDOM_WORDS_INDEX_EXPIRED);
        }

        return show(config('code.success'), '请求成功', [
            'name' => $name,
            'index' => $index,
            'index_word' => $index_word,
            'index_word_four_1' => $word_four_arr[0],
            'index_word_four_2' => $word_four_arr[1],
            'index_word_four_3' => $word_four_arr[2],
        ]);
    }

    /**
     * 生成报告图片
     */
    public function report()
    {
        $name = htmlspecialchars(trim(input('get.name/s', '匿名用户')));
        $uid = htmlspecialchars(trim(input('get.uid/s', '')));
        $index = htmlspecialchars(trim(input('get.index/s', '0')));
        $index_word_four_1 = htmlspecialchars(trim(input('get.index_word_four_1/s', '0')));
        $index_word_four_2 = htmlspecialchars(trim(input('get.index_word_four_2/s', '1')));
        $index_word_four_3 = htmlspecialchars(trim(input('get.index_word_four_3/s', '2')));
        $sign = htmlspecialchars(trim(input('get.sign/s', '1')));


        try
        {
            if ($index > count($this->words))
            {
                $index = 0;
            }
            header('Content-type: image/png');

            //画布
            $im = @imagecreatetruecolor(753, 1206) or die('Cannot initialize new GD image stream');
            //背景颜色
            $bg_color = imagecolorallocate($im, 72, 92, 176);
            imagefilledrectangle($im, 0, 0, 1500, 2668, $bg_color);// 创建画布
            //背景
            $img_bg = imagecreatefromstring(file_get_contents('./static/active_fortune_year_new/img/p8/bg.png'));
            imagecopy($im, $img_bg, 0, 0, 0, 0, imagesx($img_bg), imagesy($img_bg));

            //微信 或者 app内用户 的头像
            $filePath = RUNTIME_PATH . 'active_fortune_year_new' . DS . $uid . '.png';
            $avatar_left = 157;
            $avatar_top = 100;
            if (file_exists($filePath))
            {//文件存在
                $img_avatar = imagecreatefromstring(file_get_contents($filePath));
                imagecopy($im, $img_avatar, $avatar_left, $avatar_top, 0, 0, self::AVATAR_WIDTH, self::AVATAR_HEIGHT);
            } else
            {//文件不存在，使用默认的
                $img_avatar = imagecreatefromstring(file_get_contents('./static/active_fortune_year_new/img/p8/avatar.png'));
                imagecopy($im, $img_avatar, $avatar_left, $avatar_top, 0, 0, self::AVATAR_WIDTH, self::AVATAR_HEIGHT);
            }

            //微信 或者 app内用户 的名字
            $name_left = 240;
            $name_top = 140;
            $name_color = imagecolorallocate($im, 34, 34, 34);
            imagettftext($im, 30, 0, $name_left, $name_top, $name_color, './static/active_fortune_year/zk_font.ttf', $name);

            //随机词条 “暴富” 两个字
            $key_word = $this->words[$index];
            $left = 260;//左边距
            $key_word_color = imagecolorallocate($im, 34, 34, 34);//字颜色
            imagettftext($im, 90, 0, $left, 340, $key_word_color, './static/active_fortune_year/zk_font.ttf', $key_word);
//            ./static/active_fortune_year/zk_font.ttf

            //随机词条 “#风生水起” “#风生水起” “#风生水起” 三个四个字的
            $key_word_four1 = $this->words_four[$index_word_four_1];
            $key_word_four2 = $this->words_four[$index_word_four_2];
            $key_word_four3 = $this->words_four[$index_word_four_3];
            $left = 110;//左边距
            $width = 185;//每个字的宽度
            $key_word_four_color = imagecolorallocate($im, 129, 157, 253);//字体颜色
            $key_word_four_font_size = 25;//字体大小
            $key_word_four_y = 410;//top距离
            imagettftext($im, $key_word_four_font_size, 0, $left, $key_word_four_y, $key_word_four_color, './static/active_fortune_year/zk_font.ttf', '#' . $key_word_four1);
            imagettftext($im, $key_word_four_font_size, 0, $left + $width, $key_word_four_y, $key_word_four_color, './static/active_fortune_year/zk_font.ttf', '#' . $key_word_four2);
            imagettftext($im, $key_word_four_font_size, 0, $left + $width * 2, $key_word_four_y, $key_word_four_color, './static/active_fortune_year/zk_font.ttf', '#' . $key_word_four3);

            //星座图片
            $img_sign = imagecreatefromstring(file_get_contents('./static/active_fortune_year_new/img/p8/sign_' . $sign . '.png'));
            imagecopy($im, $img_sign, 350, 490, 0, 0, 400, 400);

            imagejpeg($im);
            imagedestroy($im);
            exit();
        }
        catch (\Exception $e)
        {
            throw new ApiException('[' . $e->getFile() . ':' . $e->getLine() . ']' . PHP_EOL . '：[name=' . $name . '&index=' . $index . '&uid=' . $uid . ']' . $e->getMessage());
        }

    }


    /**
     * 生成圆形图片
     * @param $imgpath  图片地址/支持微信、QQ头像等没有后缀的网络图
     * @param $saveName string 保存文件名，默认空。
     * @return resource 返回图片资源或保存文件
     */
    private function circleImg($imgpath, $saveName = '')
    {
        //判断文件是否已经存在，如果存在那么返回，不存在那么生成
        $filePath = RUNTIME_PATH . 'active_fortune_year_new' . DS . $saveName;
        if (file_exists($filePath))
        {
            return;
        }

        $src_img = imagecreatefromstring(file_get_contents($imgpath));
        $w = imagesx($src_img);
        $h = imagesy($src_img);
        $w = $h = min($w, $h);

        //缩放图片
        $des_w = self::AVATAR_WIDTH;
        $des_h = self::AVATAR_HEIGHT;
        //创建画布
        $zoom_img = imagecreatetruecolor($des_w, $des_h);
        //设置缩放起点
        $des_x = 0;
        $des_y = 0;
        $src_x = 0;
        $src_y = 0;
        imagecopyresampled($zoom_img, $src_img, $des_x, $des_y, $src_x, $src_y, $des_w, $des_h, $w, $h);
        //缩放图片

        $w = self::AVATAR_WIDTH;
        $h = self::AVATAR_HEIGHT;

        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);

        $r = $des_w / 2; //圆半径
        for ($x = 0; $x < $w; $x++)
        {
            for ($y = 0; $y < $h; $y++)
            {
                $rgbColor = imagecolorat($zoom_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r)))
                {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }

        //返回资源
        if (!$saveName) return $img;

        //输出图片到文件
        $settingDir = RUNTIME_PATH . 'active_fortune_year_new';
        if (!is_dir($settingDir))
        {
            if (!mkdir($settingDir, 0755, true) && !is_dir($settingDir))
            {
                throw new \RuntimeException(sprintf('Directory "%s" was not created', $settingDir));
            }
        }
        $filePath = $settingDir . DS . $saveName;

        imagepng($img, $filePath);
        //释放空间
        imagedestroy($src_img);
        imagedestroy($img);
        imagedestroy($zoom_img);
    }


    /**
     * 根据星座id，获取视频 播放地址和封面
     * @param int $sign
     * @return mixed
     * @throws \Exception
     */
    protected function getVideoWithSign($sign = 1)
    {
        if ($sign < 1 || $sign > 12)
        {
            $sign = 1;//默认白羊座视频
        }

        //星座对应着的女神动态视频id
        if (Env::get('host.name') === 'online')
        {//线上环境
            $videos = [
                1 => 508,//白羊
                2 => 509,//金牛
                3 => 512,//双子
                4 => 513,//巨蟹
                5 => 515,//狮子
                6 => 522,//处女
                7 => 523,//天秤
                8 => 524,//天蝎
                9 => 525,//射手
                10 => 526,//摩羯
                11 => 528,//水瓶
                12 => 529,//双鱼
            ];
        } else
        {//开发环境
            $videos = [
                1 => 67,
                2 => 67,
                3 => 67,
                4 => 67,
                5 => 67,
                6 => 67,
                7 => 67,
                8 => 67,
                9 => 67,
                10 => 67,
                11 => 67,
                12 => 67,//双鱼 529
            ];
        }

        // 女神动态
        $stateInfo = (new ZlGoddessState())->getInfoById($videos[$sign], ['url', 'thumb']);
        return $stateInfo;
    }

    /**
     * 解密字符串
     * @param string $data 字符串
     * @return string
     */
    protected function decryptWithOpenssl($data): string
    {
        $config = config('miniapp');
        return openssl_decrypt(base64_decode($data), $config['aes_method'], $config['aes_key'], OPENSSL_RAW_DATA, $config['aes_iv']);
    }
}
